package com.doge.walknovel.business.home.profile.topup

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.SkuDetails
import com.doge.wnpro.R
import com.doge.walknovel.analysis.analysisEvent
import com.doge.walknovel.analysis.recharge_clicked
import com.doge.walknovel.analysis.recharge_page
import com.doge.walknovel.api.model.RechargeProductInfo
import com.doge.walknovel.core.BaseActivity
import com.doge.walknovel.core.account.AccountHelper
import com.doge.walknovel.core.base.adapters.ITEM_CLICKED
import com.doge.walknovel.core.base.isRefreshing
import com.doge.wnpro.databinding.ActivityTopUpBinding
import com.doge.walknovel.payment.google.AppBillingClientLifecycle
import com.doge.walknovel.utils.appContext
import com.doge.walknovel.utils.log
import com.doge.walknovel.utils.setOnClickCallback

class TopUpActivity : BaseActivity() {
    private val binding by lazy { ActivityTopUpBinding.inflate(layoutInflater) }
    private val refer by lazy { intent.getStringExtra(EXTRA_REFER) }
    private val viewModel: TopUpViewModel by viewModels { TopUpViewModelFactory() }
    private val appBillingClient by lazy { AppBillingClientLifecycle.get() }
    private val adapter by lazy { TopUpAdapter() }
    private var inappSkuDetails: Map<String, SkuDetails>? = null // 包含google的真实价格
    private var productListInfo: List<RechargeProductInfo>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        analysisEvent(recharge_page)
        binding.confirmView.setOnClickCallback {
            handle(adapter.selected)
        }
        binding.refreshLayout.setColorSchemeResources(R.color.pull_refresh)
        binding.refreshLayout.setOnRefreshListener {
            viewModel.initialize()
        }
        binding.recyclerView.itemAnimator = null
        binding.recyclerView.layoutManager = GridLayoutManager(binding.recyclerView.context, 3)
        binding.recyclerView.adapter = adapter
        adapter.setListener(::handleAdapterCallback)
        viewModel.loading.observe(this) {
            binding.refreshLayout.isRefreshing = it.isRefreshing()
        }
        viewModel.dataList.observe(this) {
            productListInfo = it
            productListInfo?.let(::set)
        }
        viewModel.tips.observe(this) {
            binding.tip.text = it
        }
        appBillingClient.setup(lifecycle, refer = refer, silently = false)
        appBillingClient.inappSkuDetails.observe(this) {
            log("TopUp inappSkuDetails $it")
            inappSkuDetails = it
            productListInfo?.let(::set)
        }
        appBillingClient.purchaseUpdateEvent.observe(this, {
            if (it?.isNotEmpty() == true) {
                viewModel.initialize() // 刷新充值列表  // subscribing 和 consuming 可能叠加一起给
            }
        })
        viewModel.initialize()

    }

    private fun set(data: List<RechargeProductInfo>) {
        adapter.set(data.map { it.copy(realGooglePrice = inappSkuDetails?.get(it.productId)?.price) })
    }

    private fun handleAdapterCallback(action: String, item: Any?) {
        when (action) {
            ITEM_CLICKED -> adapter.select(item as? RechargeProductInfo?)
        }
    }

    private fun handle(data: RechargeProductInfo?) {
        if (data == null) return
        log("TopUp handle buy productInfo $data")
        analysisEvent(recharge_clicked)
        appBillingClient
            .launchBillingFlow(this, BillingClient.SkuType.INAPP, data.productId)
    }


    companion object {
        private const val EXTRA_REFER = "refer"

        fun start(context: Context?, refer: String) {
            if (context == null) return
            AccountHelper.requiredLogin {
                context.startActivity(Intent(context, TopUpActivity::class.java).apply {
                    putExtra(EXTRA_REFER, refer)
                    if (context == appContext) flags = Intent.FLAG_ACTIVITY_NEW_TASK
                })
            }
        }
    }
}